package com.bodu.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bodu.core.entity.CommonEntity;
import com.bodu.core.entity.ParamReq;
import com.bodu.core.entity.enums.DelFlagEnum;
import com.bodu.core.entity.enums.StatusFlagEnum;
import com.bodu.core.exception.custom.SaveException;
import com.bodu.system.entity.po.AdminPo;
import com.bodu.system.entity.po.AdminRolePo;
import com.bodu.system.entity.po.RolePo;
import com.bodu.system.entity.request.AdminRequest;
import com.bodu.system.entity.request.AdminUpdatePassRequest;
import com.bodu.system.entity.vo.AdminVo;
import com.bodu.system.entity.vo.DeptVo;
import com.bodu.system.mapper.AdminMapper;
import com.bodu.system.mapper.AdminPermitMapper;
import com.bodu.system.mapper.AdminRoleMapper;
import com.bodu.system.mapper.DeptMapper;
import com.bodu.system.service.AdminService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @since 2019-05-25
 */
@Service("adminService")
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private AdminRoleMapper adminRoleMapper;

    @Resource
    private AdminPermitMapper adminPermitMapper;

    @Resource
    private DeptMapper deptMapper;

    /**
     * 默认密码
     */
    public final static String DEFAULT_PASSWORD = "123456";

    @Override
    public Integer updateDelFlagById(Long id, Integer delFlag) {
        return adminMapper.updateDelFlagById(id, delFlag);
    }

    @Override
    public List<AdminVo> listPage(ParamReq<AdminRequest> params) {
        return adminMapper.listPage(params);
    }


    @Override
    public Integer countPage(ParamReq<AdminRequest> map) {
        return adminMapper.countPage(map);
    }

    @Override
    public AdminPo getModelByUserName(String usename) {
        if (StrUtil.isEmpty(usename)) {
            return null;
        }
        return adminMapper.getModelByUserName(usename);
    }

    @Override
    public AdminVo getModel(Long id) {
        AdminVo adminVo = adminMapper.getModelById(id);
        adminRoles(adminVo);
        // 设置单位信息
        adminVo.setDeptName(getDeptName(adminVo.getDeptId()));
        adminVo.setStatusName(StatusFlagEnum.getStatusValues(adminVo.getStatusFlag()));
        adminVo.setPass(StrUtil.EMPTY);
        return adminVo;
    }

    private void adminRoles(AdminVo adminVo) {
        List<RolePo> roles = adminRoleMapper.getRoleByAdminId(adminVo.getId());
        Set<Long> roleIds = roles.stream().filter(ObjectUtil::isNotEmpty).map(CommonEntity::getId).collect(Collectors.toSet());
        adminVo.setRoleIds(roleIds);

        String roleNames = roles.stream().map(RolePo::getRoleName).collect(Collectors.joining(","));
        adminVo.setRoleNames(roleNames);
    }

    /**
     * 设置单位名称
     *
     * @param userId 用户编号
     * @return 机构编号
     */
    private String getDeptName(Long userId) {
        DeptVo deptvo = deptMapper.getModel(userId);
        return ObjectUtil.isNotEmpty(deptvo) ? deptvo.getDeptName() : null;
    }

    @Transactional(rollbackFor = SaveException.class)
    @Override
    public Long save(AdminRequest request) {
        request.setPass(DigestUtils.md5DigestAsHex(DEFAULT_PASSWORD.getBytes()));
        adminMapper.save(request);
        updateRoles(request.getId(), request.getCreateUser(), request.getRoleIds());
        updatePermits(request.getId(), request.getCreateUser(), request.getRoleIds());
        return request.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long update(AdminRequest request) {
        updateRoles(request.getId(), request.getCreateUser(), request.getRoleIds());
        updatePermits(request.getId(), request.getCreateUser(), request.getRoleIds());
        adminMapper.updateById(request);
        return request.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updatePassword(AdminUpdatePassRequest adminUpdatePassRequest) {
        try {
            String oldPass = DigestUtils.md5DigestAsHex(adminUpdatePassRequest.getOldPassword().getBytes());
            AdminPo adminPo = adminMapper.getModel(adminUpdatePassRequest.getId());
            if (ObjectUtil.equal(adminPo.getPass(), oldPass)) {
                String newPass = DigestUtils.md5DigestAsHex(adminUpdatePassRequest.getOldPassword().getBytes());
                return adminMapper.updatePassById(adminPo.getId(), newPass);
            } else {
                return 2;
            }
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 修改角色信息
     *
     * @param userId     用户编号
     * @param createUser 创建用户
     * @param roles      角色集合
     */
    private void updateRoles(Long userId, Long createUser, Set<Long> roles) {
        // 更新用户角色表和权限表
        adminRoleMapper.updateRoleByAdminId(userId);
        AdminRolePo adminRolePo = new AdminRolePo();
        adminRolePo.setAdminId(userId);
        adminRolePo.setRoleIds(roles);
        adminRolePo.setCreateUser(createUser);
        adminRolePo.setDelFlag(DelFlagEnum.NO.getValue());
        adminRoleMapper.batchSave(adminRolePo);
    }

    /**
     * 更新权限信息
     *
     * @param userId     用户编号
     * @param createUser 创建人
     * @param roles      角色编号
     */
    private void updatePermits(Long userId, Long createUser, Set<Long> roles) {
        adminPermitMapper.updatePermitByAdminId(userId);
        adminPermitMapper.insertAdminPermits(userId, roles, createUser);
    }
}
